from django.shortcuts import render
from django.shortcuts import render
import json
from rest_framework.views import APIView
from rest_framework.views import Response
from rest_framework.permissions import IsAuthenticated,AllowAny
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from users.serializers import UserSerializer
from django.contrib.auth.hashers import make_password,check_password
from .models import *
from .serializers import *

# 用户注册
class RegisterView(APIView):
    def post(self, request, *args, **kwargs):
        serializer = UserSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=200)
        return Response(serializer.errors, status=400)
    # def post(self,request):
    #   data = request.data
    #   print(data)
    #   try:
    #     pwd_hash = make_password(data["password"])
    #     user = User.objects.create(username=data["username"],phone=data["phone"],password=data["password"])
    #     return Response({"code":200},status=200)
    #   except:
    #     return Response({"code":400},status=200)

# 重新用户登录返回函数
def jwt_response_payload_handler(token, user=None, request=None):
    '''
    :param token: jwt生成的token值
    :param user: User对象
    :param request: 请求auth_group_permissions
    '''
    return {
        'token': token,
        'user': user.username,
        'userid': user.id
    }

# 测试必须携带token才能访问接口
class UserList(APIView):
    permission_classes = [IsAuthenticated]  # 接口中加权限
    authentication_classes = [JSONWebTokenAuthentication]

    def get(self,request, *args, **kwargs):
        print(request.META.get('HTTP_AUTHORIZATION', None))
        return Response({'name':'zhangsan'})
    def post(self,request, *args, **kwargs):
        return Response({'name':'zhangsan'})

class NoTokenSee(APIView):
  permission_classes = [AllowAny]
  def get(self,request):
    print("这个接口任何人都可以访问")
    data={
      "code":200,
      "msg":"这个接口任何人都可以访问"
    }
    return Response(data,status=200)
class TokenSee(APIView):
  def get(self,request):
    print("冲会员去，再来看")
    data={
      "code":200,
      "msg":"冲会员去，再来看"
    }
    return Response(data,status=200)

class UserShow(APIView):
  def get(self,request):
    users = User.objects.filter().last()
    userser = UserSer(users)
    data = userser.data
    return Response(data,status=200)
